import Base from "./Base";
import utils from "src/utils";
import { Props, Shape } from "src/types/shape";
import { shapeType } from "src/types/drawBoard"

export interface GroupProps {
  x: number;
  y: number;
  width: number;
  height: number;
  overflow?: 'hide' | 'show';
  borderWidth?: number;
  borderColor?: string;
  bgcolor?: string;
  shapes?: Shape[];
}

export default class extends Base {
  overflow: 'hide' | 'show'
  constructor(option?: GroupProps) {
    super(shapeType.group)
    option && utils.object.Assign(option, this.props)
    this.overflow = option?.overflow || 'show'
    if (option?.shapes) {
      this.props.shapes = utils.object.Copy(option?.shapes)
    }
  }
  add(shape: Shape) {
    this.props.shapes.push(shape)
  }
  remove(shapeId: string) {
    this.props.shapes.splice(
      this.props.shapes.findIndex(shape => shape.getRgbaId() == shapeId) || -1,
      1
    )
  }
  removeAll() {
    this.props.shapes.length = 0
  }
  draw(ctx: CanvasRenderingContext2D, osCtx: OffscreenCanvasRenderingContext2D): void {
    const { x, y, width, height } = this.props

    ctx.save()
    osCtx.save()
    this.initOptions(ctx, 1)

    this.transform(ctx)
    this.transform(osCtx)

    if (this.overflow != 'show') {
      ctx.rect(x, y, width, height)
      ctx.clip()
      osCtx.rect(x, y, width, height)
      osCtx.clip()
    }

    ctx.translate(x, y)
    osCtx.translate(x, y)

    for (let i = 0; i < this.props.shapes.length; i++) {
      const shape = this.props.shapes[i];
      shape.draw(ctx, osCtx)
    }

    ctx.restore()
    osCtx.restore()

    // // 镜像画布
    this.drawMirror(osCtx)

  }
  setProps(option: Props): void {
    super.setProps(option)
  }
}